<template>
  <el-form :model="form" label-width="80px" class="form-category">
    <!-- 分类目录选择器 -->
    <el-form-item label="所属分类">
      <el-select v-model="form.category_id" placeholder="请选择所属类别">
        <el-option 
        v-for="(item, index) in categorys"
        :key="index"
        :label="item.title" 
        :value="item.category_id">
        </el-option>
      </el-select>
    </el-form-item>
    <!-- 信息输入框 -->
    <el-form-item label="培训数字">
      <el-input v-model="form.sort_id" ></el-input>
      <span class="tip">*栏目排序,排序不能小于( 0 )</span>
    </el-form-item>
    <el-form-item label="类别名称">
      <el-input v-model="form.title"></el-input>
      <span class="tip">*类别中文名称，100字符内</span>
    </el-form-item>
    <el-form-item label="类别级别">
      <el-input v-model="form.class_layet"></el-input>
      <span class="tip">*类别的级别，1:1级菜单 2：二级菜单 依次类推</span>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="onSubmit">立即创建</el-button>
      <el-button @click="handleCancel">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
export default {
  data() {
    return {
      form: {
        title: "",
        category_id: "",
        sort_id: "",
        class_layer: ""
      },
      categorys: [],
    };
  },
  methods: {
    // 创建表单的逻辑
    onSubmit() {
      // 发送新增成功的请求
      this.$axios({
        method: "POST",
        url: "/admin/category/add/goods",
        // 由于在8080端口下去请求8899端口，涉及到跨域
        withCredentials: true,
        data: this.form
      }).then(res => {
        const {message, status} = res.data;
        if(!status) {
          this.$message({
            message,
            type: "success"
          });
          this.$router.back();
        } else {
          this.$message.error(message)
        }
      })
    },
    // 取消的逻辑
    handleCancel() {
      this.$router.back();
    }
  },
  mounted() {
    // 获取所有的分类目录
    this.$axios({
      url: "/admin/category/getlist/goods"
    }).then(res => {
      const {message, status} = res.data;
      if(!status) {
        // 获取分类数据成功
        this.categorys = message.map(v => {
          return {
            ...v,
            title: v.title,
            category_id: v.category_id
          }
        })
      }
    })
  }
};
</script>

<style scoped>
.form-category {
  margin-top: 20px;
}
.form-category >>> .el-input__inner {
  text-align: left;
  text-indent: 20px;
}
.tip {
  color: rgb(173, 168, 168);
  margin-left: 20px;
}
</style>
